package com.ywb.controller;


import com.ywb.entity.EduUser;
import com.ywb.service.EduUserService;
import com.ywb.utils.JWTUtils;
import com.ywb.utils.R;
import com.ywb.utils.ValidateImageCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;

/**
 * <p>
 * 登录控制器，对应edu_user表
 * </p>
 *
 * @author ywb
 * @since 2021-05-23
 */
@Controller
@RequestMapping("/user")
public class EduUserController extends BaseController{

    @Autowired
    private EduUserService userService;

    @GetMapping("/login")
    public String login(){
        return "/user/login";
    }

    @PostMapping("/login")
    public String userLogin(Model model) throws ServletException, IOException {
        String userName = request.getParameter("username");
        String password = request.getParameter("password");
        R resultInfo = userService.userLogin(userName, password);
        if(resultInfo.getSuccess() == false){
//            登录失败，返回失败信息到login页面
//            request.setAttribute("resultInfo", resultInfo);
            model.addAttribute("resultInfo", resultInfo);
            return "/user/login";

        }

//        登录成功进入主页面:
        EduUser user = (EduUser) resultInfo.getData().get("user");
        //            根据id,username生成token的payload
        HashMap<String, String> payload = new HashMap<>();
        payload.put("id", user.getId());
        payload.put("username", user.getUsername());
//            生成token
        String token = JWTUtils.getToken(payload);
//            将token放入cookie中
        Cookie cookie = new Cookie("token", token);
//            设置cookie在为全路径
        cookie.setPath("/");
//        判断用户是否点击了记住我
        String rem = request.getParameter("rem");
        if(rem != null &&rem.equals("1")){
//            设置cookie时长为3天
            cookie.setMaxAge(3 * 24 * 60 * 60);
        }else{
//            设置cookie时长为1小时
            cookie.setMaxAge(1 * 60 * 60);
        }
//        将Cookie放入request中
        response.addCookie(cookie);
//        SpringBoot中,默认转发带redirect为重定向
        return "redirect:/index";
    }

    @PostMapping("/register")
    public String  register(EduUser user, String code, String repassword, HttpSession session){
//        1. 验证码检测
        String sessionCode = (String) session.getAttribute("code");
        if(!StringUtils.hasLength(sessionCode) || !sessionCode.equalsIgnoreCase(code)){
            session.setAttribute("msg","验证码输入错误");
            return "redirect:/user/registration.jsp";
        }
//        2.两次输入密码验证
        System.out.println(user.getPassword());
        System.out.println(repassword);
        if(!user.getPassword().equals(repassword)){
            session.setAttribute("msg","两次密码不一致");
            return "redirect:/user/registration.jsp";
        }
        user.setPassword(DigestUtils.md5DigestAsHex((user.getPassword()).getBytes(StandardCharsets.UTF_8)));
//        2.保存用户
        try {
            userService.save(user);
        }catch (DuplicateKeyException e){
            e.printStackTrace();
            session.setAttribute("msg", "该姓名已被使用");
            return "redirect:/user/registration.jsp";
        }
        return "redirect:/user/login.jsp";
    }

    @RequestMapping("/getCode")
    public void getCode(HttpSession session, HttpServletResponse response) throws IOException {
//        使用工具类生成验证码
        String securityCode = ValidateImageCodeUtils.getSecurityCode();
//        将验证码放在session会话中
        session.setAttribute("code", securityCode);
//        生成验证码图片
        BufferedImage image = ValidateImageCodeUtils.createImage(securityCode);
//        获得浏览器response的输出流
        ServletOutputStream os = response.getOutputStream();
//        输出图片到response中
        ImageIO.write(image, "png", os);
    }

    @GetMapping("/logout")
    public String logout(){
//        1. 登出的时候遍历cookie值
        Cookie[] cookies = request.getCookies();
        for(Cookie cookie : cookies){
//            2.找到token的cookie
            if(cookie.getName().equals("token")){
//                3.将其的期限设为0即可
                cookie.setPath("/");
                cookie.setMaxAge(0);
                response.addCookie(cookie);
            }
        }

        return "redirect:/user/login";
    }
}

